package com.bum.api.web.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;

import com.bum.api.web.bo.ApiBO;
import com.bum.api.web.bo.Loader;
import com.bum.api.web.util.RequestUtil;

public class JsonServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	ApiBO apiBO = Loader.getBean("apiBO", ApiBO.class);

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		process(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		process(request, response);
	}

	private void process(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String path = RequestUtil.getPath(request);

		String[] parts = StringUtils.split(path, "/", 2);
		if ("json".equals(parts[0])) {
			String json = apiBO.getJson(parts[1], RequestUtil.getParams(request), RequestUtil.getMetas(request));
			json = StringUtils.trimToEmpty(json);

			response.setContentType("application/json");
			response.setCharacterEncoding("UTF-8");

			PrintWriter out = response.getWriter();
			out.write(json);
			out.flush();
		}
	}
}
